package com.jiangyg.mall.gateway.config;

import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.gateway.support.feign.FeignBuilder;
import com.jiangyg.mall.gateway.support.feign.FeignRequestInterceptor;
import feign.Feign;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * 类描述：Feign 客户端配置
 * <p>注意：</p>
 *
 * @author jiangyg
 * @date 2022-09-01
 */
@Slf4j
@Configuration
@EnableFeignClients("com.jiangyg.mall.**.feign")
@ComponentScan("com.jiangyg.mall.**.feign.fallback")
public class FeignConfiguration {

    /**
     * 功能描述：Feign 客户端拦截器
     *
     * @return FeignRequestInterceptor Feign 客户端拦截器
     */
    @Bean
    public FeignRequestInterceptor feignRequestInterceptor() {
        Logger.info(log, () -> "[项目启动] - 注册 FeignRequestInterceptor 客户端拦截器……");
        return new FeignRequestInterceptor();
    }

    @Bean
    @Scope("prototype")
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "feign.hystrix.enabled")
    public Feign.Builder feignHystrixBuilder() {
        return new FeignBuilder();
    }

    /**
     * 功能描述：feign 调用解码器
     *
     * @return feign.codec.Decoder 解码器
     */
    @Bean
    public Decoder feignDecoder() {
        // TODO 是否有默认配置，尝试取消
        return new ResponseEntityDecoder(new SpringDecoder(() -> httpMessageConverters()));
    }

    @Bean
    public HttpMessageConverters httpMessageConverters() {
        return new HttpMessageConverters(new GateWayMappingJackson2HttpMessageConverter());
    }

    public static class GateWayMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

        GateWayMappingJackson2HttpMessageConverter() {
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.valueOf(MediaType.TEXT_HTML_VALUE + ";charset=UTF-8"));
            setSupportedMediaTypes(mediaTypes);
        }

    }

}
